package org.deng.learn.distribute.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 邓力宾
 * @date 2020/7/23 15:07
 * @desc 测试redis 分布式锁
 */
public class RedisMain {
    private static int num = 500;
    private final  static  int THREAD_NUM = 50; // 线程数
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_NUM);
    private static CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        RedisLock lock = new RedisLock();
        for(int i = 0; i < THREAD_NUM; i++){
            String requestId = "thread::"+i;
            Thread thread =  new Thread(()->{
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                boolean r = lock.lock(requestId);
                if(!r){
                    throw new RuntimeException("Get RedisLock failed");
                }
                num--;
                countDownLatch.countDown();
            });

            thread.start();
        }
        countDownLatch.await();
        System.out.println("num = " + num +" time:"+(System.currentTimeMillis() - start));
    }
}
